package org.phoenixframework.api.sys.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.phoenixframework.api.sys.util.SecurityUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2020/12/22 21:44
 * Description:
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    private final String lastModifiedBy = "lastModifiedBy";
    private final String lastModifiedDate = "lastModifiedDate";

    @Override
    public void insertFill(MetaObject metaObject) {
        String createdBy = "createdBy";
        if (metaObject.hasSetter(createdBy)) {
            this.setFieldValByName(createdBy, SecurityUtils.getUserId(), metaObject);
        }
        String createdDate = "createdDate";
        if (metaObject.hasSetter(createdDate)) {
            this.setFieldValByName(createdDate, LocalDateTime.now(), metaObject);
        }
        if (metaObject.hasSetter(lastModifiedBy)) {
            this.setFieldValByName(lastModifiedBy, SecurityUtils.getUserId(), metaObject);
        }
        if (metaObject.hasSetter(lastModifiedDate)) {
            this.setFieldValByName(lastModifiedDate, LocalDateTime.now(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(lastModifiedBy)) {
            this.setFieldValByName(lastModifiedBy, SecurityUtils.getUserId(), metaObject);
        }
        if (metaObject.hasSetter(lastModifiedDate)) {
            this.setFieldValByName(lastModifiedDate, LocalDateTime.now(), metaObject);
        }
    }
}
